'''
Author: duliang thinktanker@163.com
Date: 2024-03-02 21:15:03
LastEditors: duliang thinktanker@163.com
LastEditTime: 2024-03-24 20:20:47
FilePath: \opencv2\temp.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
import tkinter as tk
from tkinter import simpledialog, filedialog
from PIL import Image, ImageTk


class markCutRect:

    def __init__(self, root) -> None:
        #
        self.root = root
        self.canvas = None
        # 初始化矩形的初始坐标为空
        self.rect_start_x = None
        self.rect_start_y = None
        self.rect_end_x = None
        self.rect_end_y = None
        #
        self.left_button_press = False
        self.rect_id = None

        self.filename = None

    def on_button_press(self, event):
        self.rect_start_x, self.rect_start_y = event.x, event.y
        self.set_status(f"{self.rect_start_x}, {self.rect_start_y}")
        self.left_button_press = True

    def on_mouse_move(self, event):
        """处理鼠标移动事件"""
        # 获取鼠标在画布坐标系中的位置
        if self.left_button_press:
            x = event.x
            y = event.y
            # print(f"鼠标当前位置: ({x}, {y})")
            self.set_status(f"x,y: {x}, {y}")
            if self.rect_id:
                self.canvas.delete(self.rect_id)
            self.rect_id = self.canvas.create_rectangle(self.rect_start_x,
                                                        self.rect_start_y,
                                                        x,
                                                        y,
                                                        fill='',
                                                        outline='red',
                                                        width=2)
            self.canvas.update()

    def on_button_release(self, event):
        """在鼠标释放时计算矩形终点并绘制矩形"""
        # global rect_end_x, rect_end_y, left_button_press
        self.left_button_press = False
        self.rect_end_x = event.x
        self.rect_end_y = event.y
        if self.rect_start_x is not None and self.rect_start_y is not None:
            # 创建矩形，左上角坐标为start_x, start_y，右下角坐标为end_x, end_y
            rectangle_id = self.canvas.create_rectangle(self.rect_start_x,
                                                        self.rect_start_y,
                                                        self.rect_end_x,
                                                        self.rect_end_y,
                                                        fill='',
                                                        outline='red',
                                                        width=2)
            print(
                f"Rectangle drawn from ({self.rect_start_x}, {self.rect_start_y}) to ({self.rect_end_x}, {self.rect_end_y})"
            )
            input_str = simpledialog.askstring("名称", "输入名称")
            if input_str:
                print(input_str)
            else:
                self.canvas.delete(rectangle_id)
                self.canvas.update()

    def set_status(self, message):
        statusbar.config(text=message)

    def open_file(self):
        # 弹出文件选择对话框
        # global image_file, canvas
        image_file = filedialog.askopenfilename(
            title='选择图片',
            filetypes=(('PNG files', '*.png'), ('JPG files', '*.jpg'),
                       ('All files', '*.*')))
        # 打开图片（例如图片名为'image.jpg'）
        if image_file:
            # image_file = '2z.png'
            image = Image.open(image_file)

            # 将图片转换为Tkinter支持的格式
            photo = ImageTk.PhotoImage(image)

            # 创建Canvas
            self.canvas = tk.Canvas(self.root,
                                    width=image.width,
                                    height=image.height)
            # 将Canvas添加到窗口中
            self.canvas.pack(fill=tk.BOTH, expand=True)

            # 将图片加载到Canvas上
            self.canvas.create_image(0, 0, anchor='nw', image=photo)
            # 同样保持对img_tk对象的引用以避免被垃圾回收
            self.canvas.image_ref = photo
            # 为 Canvas 绑定鼠标事件
            self.canvas.bind('<ButtonPress-1>', self.on_button_press)
            self.canvas.bind('<ButtonRelease-1>', self.on_button_release)
            self.canvas.bind("<Motion>",
                             self.on_mouse_move)  # "<Motion>" 是鼠标移动事件的别名
            # canvas.update()


# 创建主窗口
root = tk.Tk()
root.title("图像标注工具")
markCut = markCutRect(root)
# 创建一个按钮，绑定打开文件的函数
open_button = tk.Button(root, text="打开文件", command=markCut.open_file)
open_button.pack()

statusbar = tk.Label(root, bd=1, relief=tk.SUNKEN, anchor=tk.W)
statusbar.pack(side=tk.BOTTOM, fill=tk.X)

# 设置初始状态信息
markCut.set_status("欢迎使用本应用！")
# 运行主循环
root.mainloop()
